<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query.fileName" placeholder="文件名" style="width: 200px;" class="filter-item" @keyup.enter.native="filter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column prop="id" align="center" label="ID" width="95px" sortable />
      <el-table-column prop="file_name" label="文件名" sortable width="200px">
        <template v-slot="{row}">
          {{ row.fileName }}
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="备注" width="200px">
        <template v-slot="{row}">
          {{ row.desc }}
        </template>
      </el-table-column>
      <el-table-column prop="url" label="URL" sortable />
      <el-table-column align="center" prop="updated_at" label="更新时间" width="160px">
        <template v-slot="{row}">
          <span>{{ row.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="160px">
        <template v-slot="{row}">
          <span>{{ row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180px">
        <template v-slot="{row, $index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="del(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :total="listQuery.totalRecords" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
        <el-form-item label="文件" prop="url" style="margin-bottom: 30px;">
          <Upload v-model="temp" list_type="text" file_size="100" :multiple="false" />
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="temp.desc" placeholder="请输入备注" style="width: 360px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, create, update, del } from '@/api/tools/upload'
import Pagination from '@/components/Pagination'
import Upload from '@/components/Upload'

export default {
  components: { Pagination, Upload },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
        }
      },
      temp: {
        id: undefined,
        url: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        url: [
          { required: true, message: '上传文件不能为空', trigger: 'change' },
          { max: 200, message: '上传文件 长度不能超过 200 个字符', trigger: 'blur' }
        ],
        desc: [
          { max: 50, message: '备注 长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        url: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制行数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    del(row, index) {
      this.$confirm('是否删除此记录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
    sortChange(column) {
      this.listQuery.orders = [{
        column: column.prop,
        asc: column.order === 'ascending'
      }]
      this.fetchData()
    }
  }
}
</script>
